<script setup>
import dayjs from 'dayjs'
import { useIntersectionObserver } from '@vueuse/core'
import useUser from '@/store/user'
import { Check } from '@element-plus/icons-vue'
import useChannel from '@/store/channel'
import { useRoute } from 'vue-router'
import useEventBus from '@/use/use-event-bus.js'
import useApp from '@/store/app'

const props = defineProps({
  message: Object,
  showCheckBox: Boolean,
  disabledFooter: Boolean,
  disabledOperation: Boolean,
  disabledDate: Boolean,
  checked: Boolean,
})
const emit = defineEmits(['openContextmenu', 'check'])
const channelStore = useChannel()
const userStore = useUser()
const appStore = useApp()
const route = useRoute()
const eventBus = useEventBus()

const messageContentRef = ref()
const { userId, id, createBy, createUser, metaData, type } = toRefs(props.message)

const isCurrentUser = computed(() => {
  return userId.value === userStore.userId
})

const timeStamp = computed(() => {
  const time = dayjs(props.message.createTime)
  const isToDay = time.isToday()
  const isThisYear = dayjs().year() === time.year()
  return isToDay ? time.format('H:mm:ss') : isThisYear ? time.format('M-D H:mm') : time.format('YYYY-M-D')
})

function onContextmenu(e) {
  e.preventDefault()
  emit('openContextmenu', { message: props.message, show: true, position: { left: e.x, top: e.y } })
}

// 发送已读消息
if (!props.disabledFooter && !isCurrentUser.value && !metaData.value.status.readFlag) {
  const fn = () => {
    const { stop } = useIntersectionObserver(messageContentRef, ([{ isIntersecting }]) => {
      if (isIntersecting) {
        const data = JSON.stringify({ action: 'read_message', data: { id: id.value } })
        appStore.imWebsocket.send(data)
        stop()
      }
    })
  }
  if (appStore.appIsFocus) {
    fn()
  } else {
    watch(
      () => appStore.appIsFocus,
      () => {
        fn()
      },
      {
        once: true,
      }
    )
  }
}

// 昵称
const nickName = computed(() => {
  return channelStore.members.find((i) => i.userId === createBy.value)?.nickName
})

function handleCheck() {
  emit('check', props.message, !props.checked)
}
</script>

<template>
  <SystemMessage v-if="type === 2" :message="props.message"></SystemMessage>
  <div
    v-else
    class="message-box-user"
    :class="{
      'current-user': isCurrentUser,
      'flag-message': metaData.status.tagFlag || route.query.jumpId === id,
      'pin-message': metaData.status.pinnedFlag,
    }"
    :message-id="id">
    <div v-if="props.showCheckBox" class="message-checkbox" :class="props.checked ? 'active' : ''" @click="handleCheck">
      <el-icon v-if="props.checked"><Check /></el-icon>
    </div>
    <el-avatar
      :src="channelStore.memberAvatarMap.get(userId)"
      :size="30"
      @click="eventBus.emit('openPostcard', userId)">
      {{ createUser?.slice(-2) }}
    </el-avatar>
    <div class="message-content">
      <div class="header">
        <div v-if="!isCurrentUser" class="user-name">{{ nickName || createUser }}</div>
        <div class="time-stamp">{{ timeStamp }}</div>
      </div>
      <div ref="messageContentRef" @contextmenu="onContextmenu" class="body">
        <MessageRender
          :message="props.message"
          :disabled-operation="props.disabledOperation"
          @contextmenu="(...arg) => onContextmenu(...arg)"></MessageRender>
        <div v-if="metaData.status.pinnedFlag" class="message-pin">
          <span class="message-fontsize">
            <SvgIcon name="im-msg-pin" size="12" style="color: #4da594"></SvgIcon>
            {{ userStore.userInfo.nickName }} Pin了这条消息，对所有群成员可见
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.message-box-user {
  @include use-flex();
  position: relative;
  padding: 5px 30% 5px 0;
  &:hover {
    .message-content .body {
      :deep(.message-render) {
        .message-operation {
          display: inline-block;
        }
      }
    }
  }
  &.current-user {
    flex-direction: row-reverse;
    padding: 5px 0 5px 30%;
    .message-checkbox {
      margin-left: 10px;
      margin-right: 0;
    }
    .message-content {
      @include use-flex(flex-end, normal, column);
      margin: 0 10px 0 0;
      .header {
        justify-content: flex-end;
      }
      .body {
        flex-direction: row-reverse;
      }
    }
  }
  &.flag-message,
  &.pin-message {
    background-color: rgba(241, 152, 56, 0.1);
  }
  .elp-avatar {
    flex-shrink: 0;
  }
  .message-checkbox {
    @include use-flex(center, center);
    border-radius: 50%;
    border: 1px solid var(--elp-color-info-light-5);
    height: 20px;
    width: 20px;
    margin-right: 10px;
    cursor: pointer;
    &.active {
      color: #fff;
      border-color: var(--elp-color-primary);
      background-color: var(--elp-color-primary);
    }
  }
  .message-content {
    margin: 0 0 0 10px;
    word-break: break-all;
    .header {
      @include use-flex(center);
      font-size: 12px;
      .user-name {
        color: var(--elp-color-info-light);
      }
      .time-stamp {
        padding-left: 10px;
        color: var(--elp-color-info-light-3);
      }
    }
    .body {
      position: relative;
      padding: 5px 0;
      min-height: 35px;
      .message-pin {
        .message-fontsize {
          @include use-flex(center);
          color: #4da594;
          svg {
            margin-right: 5px;
          }
          i {
            margin-right: 4px;
          }
        }
      }
      .loading {
        position: absolute;
        top: 50%;
        left: -20px;
        translate: 0 -50%;
        z-index: 2;
      }
    }
    .footer {
      font-size: 12px;
      color: var(--elp-color-info-light-5);
      .reply {
        cursor: pointer;
        color: var(--elp-color-primary);
      }
      .is-read {
        padding-left: 10px;
      }
    }
  }
}
</style>
